﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace Eneta.Portal.Deployment.Fields
{
    public class FieldCollection
    {
        [XmlArray("Fields")]
        [XmlArrayItem("Field")]
        public List<Field> Fields { get; set; }

        public static FieldCollection Deserialize(string xml)
        {
            FieldCollection fields;
            XmlSerializer fieldCollection = new XmlSerializer(typeof(FieldCollection));

            using (var stream = new MemoryStream(xml.Length))
            {
                var bytes = Encoding.UTF8.GetBytes(xml);
                stream.Write(bytes, 0, bytes.Length);
                stream.Seek(0, SeekOrigin.Begin);

                fields = (FieldCollection)fieldCollection.Deserialize(stream);
            }
            return fields;
        }


        public static FieldCollection Deserialize(byte[] contents)
        {
            FieldCollection fields;
            XmlSerializer fieldCollection = new XmlSerializer(typeof(FieldCollection));

            using (var stream = new MemoryStream(contents.Length))
            {
                var bytes = contents;
                stream.Write(bytes, 0, bytes.Length);
                stream.Seek(0, SeekOrigin.Begin);

                fields = (FieldCollection)fieldCollection.Deserialize(stream);
            }
            return fields;
        }

        public string Serialize()
        {
            string fieldCollection;
            using (var stream = new MemoryStream())
            {
                XmlSerializer data = new XmlSerializer(typeof(FieldCollection));
                data.Serialize(stream, this);

                stream.Seek(0, SeekOrigin.Begin);
                using (var reader = new StreamReader(stream))
                {
                    fieldCollection = reader.ReadToEnd();
                }
            }
            return fieldCollection;
        }
    }
}
